<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="600px"
    @ok="handleSubmit"
    @close="handlerCancel"
  >
    <BasicForm @register="registerForm">
      <template #menu>
        <BasicTree
          v-if="treeData.length"
          :treeData="treeData"
          :replaceFields="{ title: 'menuName', key: 'id' }"
          checkable
          title="菜单分配"
          :defaultExpandLevel="1"
          @check="handleCheck"
          :checkedKeys="checkedIds"
        />
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './role.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasicTree, TreeItem } from '/@/components/Tree';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { createRole, updateRole } from '/@/api/sys/role';
  import { queryMenuList } from '/@/api/sys/menu';

  export default defineComponent({
    name: 'RoleDrawer',
    components: { BasicDrawer, BasicForm, BasicTree },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const { createMessage } = useMessage();
      const isUpdate = ref(true);
      const treeData = ref<TreeItem[]>([]);
      const halfCheckedKeys = ref([]);
      const checkedIds = ref([]);
      const roleId = ref(0);

      function handleCheck(checkedKeys, e) {
        halfCheckedKeys.value = [...checkedKeys, ...e.halfCheckedKeys];
      }

      const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
        labelWidth: 90,
        schemas: formSchema,
        showActionButtonGroup: false,
      });

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        resetFields();
        setDrawerProps({ confirmLoading: false });
        // 需要在setFieldsValue之前先填充treeData，否则Tree组件可能会报key not exist警告
        if (unref(treeData).length === 0) {
          treeData.value = (await queryMenuList()) as any as TreeItem[];
        }
        isUpdate.value = !!data?.isUpdate;
        if (unref(isUpdate)) {
          setFieldsValue({
            ...data.record,
          });
          checkedIds.value = data.record.menuIds;
          halfCheckedKeys.value = data.record.menuIds;
          roleId.value = data.record.id;
        }
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增角色' : '编辑角色'));
      async function handleSubmit() {
        try {
          if (!halfCheckedKeys.value.length) {
            createMessage.warn('请选择菜单权限');
            return;
          }
          if (!isUpdate.value) {
            let values = await validate();
            values = Object.assign({ ...values }, { menu: halfCheckedKeys.value });
            setDrawerProps({ confirmLoading: true });
            await createRole(values);
            createMessage.success('新增成功！');
          } else {
            let values = await validate();
            values = Object.assign(
              { ...values },
              { menu: halfCheckedKeys.value },
              { id: roleId.value }
            );
            setDrawerProps({ confirmLoading: true });
            await updateRole(values);
            createMessage.success('更新成功！');
          }
          closeDrawer();
          emit('success');
        } finally {
          setDrawerProps({ confirmLoading: false });
          checkedIds.value = [];
          halfCheckedKeys.value = [];
          roleId.value = 0;
        }
      }

      // 弹窗关闭时重置halfCheckedKeys
      function handlerCancel() {
        halfCheckedKeys.value = [];
        checkedIds.value = [];
      }

      return {
        registerDrawer,
        handleCheck,
        registerForm,
        getTitle,
        handleSubmit,
        handlerCancel,
        treeData,
        checkedIds,
      };
    },
  });
</script>
